const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const { v4: uuidv4 } = require('uuid');
const response = require('../utils/response');

const router = express.Router();

/**
 * 配置文件存储
 * @type {multer.StorageEngine}
 */
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // 确保这个目录存在
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名
    const uniqueName = `${uuidv4()}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  }
});

/**
 * 文件类型过滤
 * @param {Express.Request} req - 请求对象
 * @param {Express.Multer.File} file - 上传的文件
 * @param {function} cb - 回调函数
 */
const fileFilter = (req, file, cb) => {
  // 允许的文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件类型！'), false);
  }
};

const upload = multer({ 
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  }
});

/**
 * 上传文件
 * @route POST /upload
 * @returns {Object} 统一格式的响应对象
 */
router.post('/', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json(response(false, '没有文件被上传', null, 400));
    }

    const fileUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`;
    
    res.json(response(true, '文件上传成功', {
      url: fileUrl,
      filename: req.file.filename
    }));
  } catch (error) {
    res.status(500).json(response(false, '文件上传失败', null, 500));
  }
});

/**
 * 更新文件
 * @route PUT /upload/:filename
 * @returns {Object} 统一格式的响应对象
 */
router.put('/:filename', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json(response(false, '没有文件被上传', null, 400));
    }

    const oldFilePath = path.join(__dirname, '../uploads', req.params.filename);
    
    try {
      await fs.unlink(oldFilePath);
    } catch (error) {
      console.error('删除旧文件失败:', error);
    }

    const fileUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`;
    
    res.json(response(true, '文件更新成功', {
      url: fileUrl,
      filename: req.file.filename
    }));
  } catch (error) {
    res.status(500).json(response(false, '文件更新失败', null, 500));
  }
});

/**
 * 删除文件
 * @route DELETE /upload/:filename
 * @returns {Object} 统一格式的响应对象
 */
router.delete('/:filename', async (req, res) => {
  try {
    const filePath = path.join(__dirname, '../uploads', req.params.filename);
    await fs.unlink(filePath);
    
    res.json(response(true, '文件删除成功'));
  } catch (error) {
    res.status(500).json(response(false, '文件删除失败', null, 500));
  }
});

module.exports = router; 